<?php
/*控制器基类*/
namespace app\index;

use \think\Config;
use \think\Db;
use \think\Request;
use \think\Session;

class Controller extends \think\Controller
{
    protected $user = null;

    //初始化
    public function _initialize()
    {
        //设置模版主题
        $this->setTheme();
        //检查是否需要登录
        $this->checkLogin();
        //获取用户信息
        $this->getUser();
        //自动分红触发
        $this->autoAbonus();
    }

    //检查是否需要登录
    private function checkLogin()
    {
        if (Session::has('user')) {
            return true;
        }
        $reqAction = strtolower($this->request->module()) . '/' . strtolower($this->request->controller()) . '/' . strtolower($this->request->action());
        $notLogin  = Config::get('not_login');
        if (in_array($reqAction, $notLogin)) {
            return true;
        }
        if (!Request::instance()->isAjax()){
            $this->redirect('index/user/login');
        }
    }

    //获取用户信息
    protected function getUser()
    {
        if (Session::has('user')) {
            $user          = Db::name('user')->find(Session::get('user.user_id'));
            $this->user = $user;
            $this->assign('U', $user);
        }
    }

    //设置模版主题
    protected function setTheme()
    {
        //$theme    = 'default'; //PC模版
        $theme    = 'mobile';  //WAP模版
        if(Request::instance()->isMobile()){
            $theme    = 'mobile';
        }
        $viewPath = APP_PATH . Request::instance()->module() . DS . 'view' . DS . $theme . DS;
        $this->view->engine([
            'view_path'       => $viewPath,
            'taglib_pre_load' => 'app\common\taglib\Html']);
        $this->assign('theme', $theme);
    }

    //验证token
    protected function verifyToken($token, $clear = false)
    {
        if (Session::get('__token__') !== $token) {
            return false;
        } else {
            if ($clear) {
                Session::set('__token__', null);
            }
            return true;
        }
    }

    //设置支付密码
    protected function setPayPwd($jump = '')
    {
        if(empty($this->user['password2'])){
            $this->redirect(url('index/user/pwd', ['id' => $this->user['id'],'jump'=>urlencode($jump)]));
        }else{
            return true;
        }
    }

    //验证支付密码
    protected function validatePwd($pwd)
    {
        $pwd = md5(md5($this->user['id'].$pwd));
        if($pwd == $this->user['password2']){
            return true;
        }
        return false;
    }

    //自动分红
    protected function autoAbonus()
    {
        $config = config('abonus');
        $today  = strtotime(date("Y-m-d")); //今天开始时间
        if ($config['is_abonus']) {
            //如果已经有记录，则说明已经执行过分红了
            if (Db::name('day_record')->where('date', $today)->count()) {
                return true;
            }
            //文件锁，避免并发
            if(is_file('./abonus.lock')){
                return true;
            }else{
                file_put_contents('./abonus.lock','');
            }
            $todayPrice = sprintf("%.2f", $config['min_rand'] + mt_rand() / mt_getrandmax() * ($config['max_rand'] - $config['min_rand']));
            $todayAbonusPrice = $todayPrice;

            $where['last_time'] = ['<', $today];
            $where['status']    = 1;
            $mainAccount        = Db::name('main_account')->where($where)->select();
            $sonAccount         = Db::name('son_account')->where($where)->select();

            //主账户分红
            if ($mainAccount) {
                $todayMainTotal = 0;
                foreach ($mainAccount as $key => $val) {
                    $status = 1;
                    if ($val['total'] + $todayPrice >= $config['main_out']) {
                        $todayPrice = $config['main_out'] - $val['total'];
                        $status     = 2; //出局
                    }
                    $todayMainTotal += $todayPrice;

                    //分放分红
                    // $message = "我的账户【{$val['name']}】每日分红奖励{$todayPrice}";
                    // inc_money($val['user_id'], $val['name'], 'money', $todayPrice, $message, 4);

                    //更新分红账户
                    Db::name('main_account')->where('id', $val['id'])->update([
                        'day'       => $val['day'] + 1,
                        'money'     => $todayPrice,
                        'total'     => $val['total'] + $todayPrice,
                        'balance'   => $val['balance'] + $todayPrice,
                        'status'    => $status,
                        'last_time' => time(),
                    ]);

                    //出局了的账户重新创建
                    if ($status == 2) {
                        Db::name('main_account')->insert([
                            'name'    => $val['name'],
                            'user_id' => $val['user_id'],
                            'price'   => $config['main_price']
                        ]);
                    }
                }

                //扣除市场分红基金
                if ($todayMainTotal) {
                    Db::name('fund')->where('1=1')->setDec('abonus', $todayMainTotal);
                    Db::name('fund_record')->insert([
                        'reason' => date('Y-m-d') . '主账户每日分红支出' . $todayMainTotal . '元',
                        'amount' => $todayMainTotal,
                        'type'   => 'abonus',
                        'time'   => time(),
                    ]);
                }
            }
            //子账户分红
            if ($sonAccount) {
                $todaySonTotal = 0;
                foreach ($sonAccount as $key => $val) {
                    $status = 1;
                    if ($val['total'] + $todayPrice >= $config['son_out']) {
                        $todayPrice = $config['main_out'] - $val['total'];
                        $status     = 2; //出局
                    }
                    $todaySonTotal += $todayPrice * $val['num'];

                    $sonMoney = sprintf("%.2f", $val['num'] * $todayPrice);

                    //分放分红
                    // $message  = "复投账户【{$val['username']}】每日分红奖励{$sonMoney}";
                    // inc_money($val['user_id'], $val['username'], 'money', $sonMoney, $message, 4);

                    //更新复投分红账户
                    Db::name('son_account')->where('id', $val['id'])->update([
                        'day'       => $val['day'] + 1,
                        'money'     => $sonMoney,
                        'total'     => $val['total'] + $sonMoney,
                        'balance'   => $val['balance'] + $sonMoney,
                        'status'    => $status,
                        'last_time' => time(),
                    ]);
                }

                //扣除市场分红基金
                if ($todaySonTotal) {
                    Db::name('fund')->where('1=1')->setDec('abonus', $todaySonTotal);
                    Db::name('fund_record')->insert([
                        'reason' => date('Y-m-d') . '子账户每日分红支出' . $todaySonTotal . '元',
                        'amount' => $todaySonTotal,
                        'type'   => 'abonus',
                        'time'   => time(),
                    ]);
                }

            }
            //释放文件锁
            unlink('./abonus.lock');

            //分红完毕，记录日期和价格
            Db::name('day_record')->insert(['date' => $today, 'price' => $todayAbonusPrice]);
        }
    }

}
